﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Power.Models;
using Power.View;
using Power.View.Dialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Power.ViewModel
{
    public class SectionManagementViewModel : ViewModelBase
    {
        public SectionManagement model;
        public SectionManagementViewModel(SectionManagement model)
        {
            this.model = model;
            this.model.page.PageUpdated += Page_PageUpdated;
            model.SectionDataGrid1.PreviewKeyDown += Model_KeyDown;
            model.SectionDataGrid1.SelectionChanged += SectionDataGrid1_SelectionChanged;
            model.SectionDataGrid1.CellEditEnding += SectionDataGrid1_CellEditEnding;
            
            Delete = new RelayCommand(OnDelete);
            CheckBoxClick = new RelayCommand<object>(OnCheckBoxClick);
            Data = new SectionManagementViewModelEntity()
            {
                PipManaEntityList = new ObservableCollection<PipManaEntity>(),
                AreaSelectList = Common.Common.GetAreaSelectList(),
                BlockSelectList = Common.Common.GetBlockSelectList(),
                WorkSelectList = Common.Common.GetWorkSelectList(),
                BatchSelectList = Common.Common.GetBatchSelectList(),
            };
            for (int i = 1; i < 11; i++)
            {
                var item = new PipManaEntity
                {
                    Id = $"{i}",
                    Pip = new PipEntity()
                    {
                        Type = $"管段类型{i}",
                        Mat = $"管段材质{i}",
                        Diameter = i * 10,
                        AreaParam = $"地区参数{i}",
                        SolidParam = $"土质参数{i}",
                        BuildDate = $"{2000 + i}"
                    },
                    StartWell = new WellEntity()
                    {
                        No = $"起始井号{i}",
                        Type = $"起始井类型{i}",
                        FuncType = $"起始井功能类型{i}",
                        Mat = $"起始井材质{i}",
                        Problem = $"起始井基本问题{i}",
                    },
                    EndWell = new WellEntity()
                    {
                        No = $"终止井号{i}",
                        Type = $"终止井类型{i}",
                        FuncType = $"终止井功能类型{i}",
                        Mat = $"终止井材质{i}",
                        Problem = $"终止井基本问题{i}",
                    }
                };
                Data.PipManaEntityList.Add(item);
            }
        }

        private void Page_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            var currentPage = e.Info;
        }

        private void SectionDataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //foreach (var item in Data.PipManaEntityList)
            //{
            //    item.IsSelectedFlag = false;
            //}
            //var selectedList = this.model.SectionDataGrid1.SelectedItems;
            //if (selectedList != null || selectedList.Count > 0)
            //{
            //    for (int i = 0; i < selectedList.Count; i++)
            //    {
            //        var item = selectedList[i] as PipManaEntity;
            //        item.IsSelectedFlag = true;
            //    }
            //}

         }
        
        /// <summary>
        /// 删除选中项
        /// </summary>
        public void DeleteSelectedItems()
        {
            var selectedList = Data.PipManaEntityList.Where(p=>p.IsSelectedFlag==true).ToList();
            if (selectedList == null || selectedList.Count == 0)
            {
                MessagePrompt box = new MessagePrompt("请选择要删除的行");
                box.ShowDialog();
                return;
            }
            {
                MessagePrompt box = new MessagePrompt("是否确认删除？", true);
                var result = box.ShowDialog();
                if (result == true)
                {
                    for (int i = 0; i < selectedList.Count; i++)
                    {
                        var item = selectedList[i] as PipManaEntity;
                        Data.PipManaEntityList.Remove(item);
                        //i--;
                    }
                }
            }
        }
        private void Model_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                e.Handled = true;

                DeleteSelectedItems();
            }
        }

        private void SectionDataGrid1_CellEditEnding(object sender, System.Windows.Controls.DataGridCellEditEndingEventArgs e)
        {
            if (e.EditingElement is TextBox)
            {
                string newValue = (e.EditingElement as TextBox).Text;
                var item = this.model.SectionDataGrid1.SelectedItem as PipManaEntity;
                if (item != null)
                {
                    PipManaEntity dataItem = Data.PipManaEntityList.FirstOrDefault(a => a.Id == item.Id);
                    string[] arr = e.Column.SortMemberPath.Split('.');
                    //二级关联属性
                    var tModel = dataItem.GetType().GetProperty(arr[0]).GetValue(dataItem, null);
                    var tPro = tModel.GetType().GetProperty(arr[1]);
                    var oldValue = Convert.ToString(tPro.GetValue(tModel, null));
                    if (oldValue != newValue)
                    {
                        //判断数据类型
                        if (tPro.PropertyType.Equals(typeof(int)))
                        {
                            int v;
                            if (int.TryParse(newValue, out v))
                            {
                                tPro.SetValue(tModel, v);
                            }
                            else
                            {
                                tPro.SetValue(tModel, 0);
                            }

                        }
                        else if (tPro.PropertyType.Equals(typeof(double)))
                        {
                            double v;
                            if (double.TryParse(newValue, out v))
                            {
                                tPro.SetValue(tModel, v);
                            }
                            else
                            {
                                tPro.SetValue(tModel, 0);
                            }
                            tPro.SetValue(tModel, Convert.ToDouble(newValue));
                        }
                        else
                        {
                            tPro.SetValue(tModel, newValue);
                        }
                        MessagePrompt box = new MessagePrompt("更新成功");
                        box.ShowDialog();
                    }
                }
            }
            //if (e.EditingElement is TextBox)
            //{
            //    string newValue = (e.EditingElement as TextBox).Text;
            //    var item = this.model.SectionDataGrid1.SelectedItem as PipManaEntity;
            //    if (item != null)
            //    {
            //        //更新数据库
            //        MessageBox.Show($"更新成功", "提示");
            //    }
            //}
            
        }

        private void OnDelete()
        {
            DeleteSelectedItems();
        }
        private void OnCheckBoxClick(object obj)
        {
            var item = Data.PipManaEntityList.Where(p => p.Id == obj.ToString()).FirstOrDefault();
            if (item != null)
            {
                item.IsSelectedFlag = !item.IsSelectedFlag;
            }
            //var item = obj as PipManaEntity;
            //if (item != null && item.IsSelectedFlag)
            //{ 
            //    this.model.SectionDataGrid1.SelectedItems.Remove(item);
            //}
        }

        private bool checkBoxIsChecked;
        public bool CheckBoxIsChecked
        {
            get
            {
                return checkBoxIsChecked;
            }
            set
            {
                checkBoxIsChecked = value;
                ChangedSelecgedFlags();
                RaisePropertyChanged();
                RaisePropertyChanged("Data.EvaluateList");
            }
        }

        private void ChangedSelecgedFlags()
        {
            foreach (var e in Data.PipManaEntityList)
                e.IsSelectedFlag = CheckBoxIsChecked;
            //if (checkBoxIsChecked)
            //{
            //    this.model.SectionDataGrid1.SelectedItems.Clear();
            //    foreach (var item in this.model.SectionDataGrid1.Items)
            //    {
            //        this.model.SectionDataGrid1.SelectedItems.Add(item);
            //    }
            //}
            //else
            //{
            //    this.model.SectionDataGrid1.SelectedItems.Clear();
            //}
        }

        public int PageIndex { get; set; } = 1;

        private PipManaEntity selectedItem;
        public PipManaEntity SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                selectedItem = value;
                RaisePropertyChanged();
            }
        }

        #region Command
        public RelayCommand Delete { get; private set; }
        public RelayCommand<object> CheckBoxClick { get; private set; }
        #endregion

        #region 数据绑定
        public SectionManagementViewModelEntity Data { get; private set; }
        #endregion
    }
}
